package com.example.yls.android_sql;

import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import java.io.File;

public class MainActivity extends AppCompatActivity {
    private Button btnCreateDB;
    private Button btnCreateTable;
    private Button btnInsert;
    private SQLiteDatabase db;
    private EditText edtName;
    private EditText edtNo;
    private EditText edtAge;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
   
        btnCreateDB = findViewById(R.id.btn_createSql);
        btnCreateTable = findViewById(R.id.btn_createStudent);
        btnInsert = findViewById(R.id.btn_insertSql);
        edtName = findViewById(R.id.edt_Name);
        edtAge = findViewById(R.id.edt_Age);
        edtNo = findViewById(R.id.edt_No);


        btnCreateDB.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View view) {
              createOrOpenDB();
          }
        });


        btnInsert.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View view) {

                  btnInsert("1001","su",19);
              }
          });


          btnCreateTable.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View view) {
                  btnCreateTable();
              }
          });
              }

      private void btnInsert(String no, String name, int age) {
          if(db == null){
              createOrOpenDB();
          }
        /*  第一种
*/      /*    String sql = "insert into student values ('" + no + "','" + name + "'," + age + ")";
          db.execSQL(sql);*/

/*第二种*/
          ContentValues values = new ContentValues();
          values.put("stuno",no);
          values.put("name",name);
          values.put("age",age);
          db.insert("student",null,values);

      }

    private void btnCreateTable() {
        if(db == null){
            createOrOpenDB();
        }
        String sql = "create table if not exists student" +
                " (stuno varchar(20),name varchar(20)," + " age int)";
      db.execSQL(sql);

    }

    private void createOrOpenDB() {
      String path = getFilesDir().getAbsolutePath()
              + File.separator + "stu.db";

        db = SQLiteDatabase.openOrCreateDatabase(path,null);

    }
}
